# 盘点
from django.http import JsonResponse
from web.models import Inventory, InventoryDetail, Users, Product
from web.apis import tools
from django import forms
from django.forms.models import model_to_dict
from django.views.decorators.csrf import csrf_exempt

# 盘点表单
class InventoryForm(forms.ModelForm):
    class Meta:
        model = Inventory
        fields = ['inventory_type', 'inventory_user', 'remark']

# 盘点详情表单
class InventoryDetailForm(forms.ModelForm):
    class Meta:
        model = InventoryDetail
        fields = ['inventory', 'product', 'inventory_number', 'inventory_actual_number', 'inventory_difference_number', 'inventory_difference_reason', 'remark']

# 创建盘点单
@csrf_exempt
def create_inventory(request):
    if request.method == 'POST':
        form = InventoryForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                inventory = form.instance
                inventory_dict = model_to_dict(inventory)
                inventory_dict['create_time'] = inventory.create_time.strftime('%Y-%m-%d %H:%M:%S')
                inventory_dict['update_time'] = inventory.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg='创建盘点单成功', data=inventory_dict))
            except Exception as e:
                return JsonResponse(tools.ReturnData(code=400, msg=f'保存盘点单失败: {str(e)}'))
        else:
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f'{error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 获取盘点单列表
@csrf_exempt
def get_inventory_list(request):
    if request.method == 'GET':
        try:
            inventories = Inventory.objects.all().order_by('-create_time')
            inventory_list = []
            for inv in inventories:
                inv_dict = model_to_dict(inv)
                inv_dict['create_time'] = inv.create_time.strftime('%Y-%m-%d %H:%M:%S')
                inv_dict['update_time'] = inv.update_time.strftime('%Y-%m-%d %H:%M:%S')
                # 关联用户
                if inv.inventory_user:
                    user = Users.objects.filter(id=inv.inventory_user.id).first()
                    inv_dict['inventory_user_name'] = user.username if user else ''
                inventory_list.append(inv_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取盘点单列表成功', data=inventory_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取盘点单列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 获取单个盘点单
@csrf_exempt
def get_inventory(request, inventory_id):
    if request.method == 'GET':
        try:
            inv = Inventory.objects.filter(inventory_id=inventory_id).first()
            if not inv:
                return JsonResponse(tools.ReturnData(code=400, msg='盘点单不存在'))
            inv_dict = model_to_dict(inv)
            inv_dict['create_time'] = inv.create_time.strftime('%Y-%m-%d %H:%M:%S')
            inv_dict['update_time'] = inv.update_time.strftime('%Y-%m-%d %H:%M:%S')
            # 关联用户
            if inv.inventory_user:
                user = Users.objects.filter(id=inv.inventory_user.id).first()
                inv_dict['inventory_user_name'] = user.username if user else ''
            # 盘点详情
            details = InventoryDetail.objects.filter(inventory=inv)
            detail_list = []
            for detail in details:
                detail_dict = model_to_dict(detail)
                detail_dict['product_name'] = detail.product.name if detail.product else ''
                detail_list.append(detail_dict)
            inv_dict['details'] = detail_list
            return JsonResponse(tools.ReturnData(code=200, msg='获取盘点单成功', data=inv_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取盘点单失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 删除盘点单
@csrf_exempt
def delete_inventory(request, inventory_id):
    if request.method == 'DELETE':
        try:
            inv = Inventory.objects.filter(inventory_id=inventory_id).first()
            if not inv:
                return JsonResponse(tools.ReturnData(code=400, msg='盘点单不存在'))
            inv.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除盘点单成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除盘点单失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

# 更新盘点单
@csrf_exempt
def update_inventory(request, inventory_id):
    if request.method == 'POST':
        try:
            inv = Inventory.objects.filter(inventory_id=inventory_id).first()
            if not inv:
                return JsonResponse(tools.ReturnData(code=400, msg='盘点单不存在'))
            form = InventoryForm(request.POST, instance=inv)
            if form.is_valid():
                form.save()
                inv_dict = model_to_dict(form.instance)
                inv_dict['create_time'] = form.instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
                inv_dict['update_time'] = form.instance.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg='更新盘点单成功', data=inv_dict))
            else:
                error_msg = tools.get_first_error(form)
                return JsonResponse(tools.ReturnData(code=400, msg=f'{error_msg}'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'更新盘点单失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 创建盘点详情
@csrf_exempt
def create_inventory_detail(request):
    if request.method == 'POST':
        form = InventoryDetailForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                detail = form.instance
                detail_dict = model_to_dict(detail)
                detail_dict['product_name'] = detail.product.name if detail.product else ''
                return JsonResponse(tools.ReturnData(code=200, msg='创建盘点详情成功', data=detail_dict))
            except Exception as e:
                return JsonResponse(tools.ReturnData(code=400, msg=f'保存盘点详情失败: {str(e)}'))
        else:
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f'{error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 获取盘点详情列表（可选：按盘点单过滤）
@csrf_exempt
def get_inventory_detail_list(request):
    if request.method == 'GET':
        try:
            inventory_id = request.GET.get('inventory_id')
            if inventory_id:
                inventory = Inventory.objects.filter(inventory_id=inventory_id).first()
                if not inventory:
                    return JsonResponse(tools.ReturnData(code=400, msg='盘点单不存在'))
                details = InventoryDetail.objects.filter(inventory=inventory)
            else:
                details = InventoryDetail.objects.all()
            detail_list = []
            for detail in details:
                detail_dict = model_to_dict(detail)
                detail_dict['product_name'] = detail.product.name if detail.product else ''
                detail_list.append(detail_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取盘点详情列表成功', data=detail_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取盘点详情列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 获取单个盘点详情
@csrf_exempt
def get_inventory_detail(request, inventory_id):
    if request.method == 'GET':
        try:
            detail = InventoryDetail.objects.filter(inventory=inventory_id).first()
            if not detail:
                return JsonResponse(tools.ReturnData(code=400, msg='盘点详情不存在'))
            detail_dict = model_to_dict(detail)
            detail_dict['product_name'] = detail.product.name if detail.product else ''
            return JsonResponse(tools.ReturnData(code=200, msg='获取盘点详情成功', data=detail_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取盘点详情失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 更新盘点详情
@csrf_exempt
def update_inventory_detail(request, inventory_id):
    if request.method == 'POST':
        try:
            detail = InventoryDetail.objects.filter(inventory=inventory_id).first()
            if not detail:
                return JsonResponse(tools.ReturnData(code=400, msg='盘点详情不存在'))
            form = InventoryDetailForm(request.POST, instance=detail)
            if form.is_valid():
                form.save()
                detail_dict = model_to_dict(form.instance)
                detail_dict['product_name'] = form.instance.product.name if form.instance.product else ''
                return JsonResponse(tools.ReturnData(code=200, msg='更新盘点详情成功', data=detail_dict))
            else:
                error_msg = tools.get_first_error(form)
                return JsonResponse(tools.ReturnData(code=400, msg=f'{error_msg}'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'更新盘点详情失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 删除盘点详情
@csrf_exempt
def delete_inventory_detail(request, inventory_id):
    if request.method == 'DELETE':
        try:
            detail = InventoryDetail.objects.filter(inventory=inventory_id).first()
            if not detail:
                return JsonResponse(tools.ReturnData(code=400, msg='盘点详情不存在'))
            detail.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除盘点详情成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除盘点详情失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))
